//引用axios
import axios from 'axios'
//引入封装请求的API
import service from './contactApi'
import {Toast} from 'vant'

// service 循环遍历输出不同的请求方法
//创建请求实例
let instance = axios.create({
    baseURL: 'http://localhost:5000/',
    contentType: "text/html;charset=utf8",
    dataType: "json",
    timeout: 1000
})
//声明请求的HTTP对象;
const Http = {}; //包裹请求方法的容器

//请求格式或参数的统一
for(let key in service)
{    
    let api = service[key];
    
    Http[key] = async function(
        params, //请求参数get,url; post,patch,put(data)
        isFormData = false,  //是否form-data请求
        config = {}
    ) {
       //let url = api.url
       let newParams = {}
       
       if(params && isFormData){
           newParams = new FormData()
           for(let i in params){
               newParams.append(i,params[i])
           }
       }else {
           newParams = params
       }

       //不同请求判断
       let response = {}; //请求响影的值；
       if(api.method ==='post' ||api.method ==='put' ||api.method =='patch'){
           try{
               response = await instance[api.method](api.url,newParams,config)
           }catch(err){
               response = err
           }

       }else if (api.method ==='delete' || api.method ==='get') {
           config.params = newParams
           try{
               //instance[api.method] ---这一部分是获取Hanson名;
               //(api.url,config) 为函数体，其中第1上参数为url,第二个参数为传递的params参数；
               response = await instance[api.method](api.url,config)
           }catch(err){
               console.log(err)
           }
       }
       return response
    } // end function
}
//请求拦截器
//config 为请求的信息，封装有表头信息;
instance.interceptors.request.use(config=>{
    Toast.loading({
        mask: false,
        duration: 0,
        forbidClick: true,  //禁止点击
        message: '加载中.....'
    })
    //发起请求前
    return config
}, ()=>{
    Toast.clear()
    Toast('请求错误，请稍后重试')

})
//请求响应的结果
//res为请求响应的结果；
instance.interceptors.response.use(res=>{
    console.log('status',res.status)
    if(res.status === 200)
    {
        Toast.clear()
        return res.data
    }
    else
    {
        Toast('请求错误，请稍后重试')
    }
   
},()=>{
   Toast.clear()
   Toast('请求错误，请稍后重试')
})

export default Http